# build type = DEBUG | RELEASE
BUILD_TYPE ?= DEBUG
ifeq ($(BUILD_TYPE), RELEASE)
OPTIMIZE_LEVEL = -O2
else
OPTIMIZE_LEVEL = -O0
endif

# specify version id
GIT_BRANCH = $(shell git rev-parse --abbrev-ref HEAD)
GIT_COMMIT_ID = $(shell git rev-parse --short HEAD)
VERSION_ID = $(GIT_BRANCH)-$(GIT_COMMIT_ID)

MARCOS = -DVERSION_INFO=\"$(VERSION_ID)\"

CSRC = $(wildcard src/*.c)

SRC_NAME_WITH_DIR = $(basename $(CSRC))
SRC_OBJS = $(addsuffix .o, $(SRC_NAME_WITH_DIR))
SRC_DEPS = $(SRC_OBJS:.o=.d)

TARGET = main.exe

.PHONY:print_version clean

default : print_version $(TARGET)

$(TARGET) : $(SRC_OBJS)
	@echo "link $(TARGET)"
	@gcc $(SRC_OBJS) -o $@

%.o : %.c %.d
	@echo "compile $<"
	@gcc $(MARCOS) $(OPTIMIZE_LEVEL) -g -c $< -o $@

%.d : %.c
	@(set -e; \
	rm -f $@; \
	gcc -MM $< > $@.$$$$; \
 	sed 's,.*\.o:,$*.o $@: ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$)

-include $(SRC_DEPS)

print_version:
	@echo "BUILD_TYPE=$(BUILD_TYPE)"
	@echo "GIT_BRANCH=$(GIT_BRANCH)"
	@echo "GIT_COMMIT_ID=$(GIT_COMMIT_ID)"
	@echo "VERSION_ID=$(VERSION_ID)"

clean:
	@rm -f $(SRC_OBJS) $(TARGET) $(SRC_DEPS)
	@find . -name *.d.* -delete
